#!/usr/bin/env python3
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
import time
import random
# import demjson

#1、桥接webrtc
#2、 录音、json cdr
#3、webrtc需要的180/183，200
#注： 未测试

# call_prix_dict = {
#     '1': '90000011',  # 广州
#     '2': '90000013',  # 东莞
#     '3': '90000012'  # 佛山
# }
record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                          "/cloudcall_file/rec_20051/freeswitchRecordFile/"]

def handler(session, args):  # args is string
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")

    if args is None:
        freeswitch.console_log("info", "call %s has no target call number in args param\n" % uuid)
        session.hangup("UNALLOCATED_NUMBER")
        return

    freeswitch.console_log("info", "call %s args string is: %s \n" % (uuid, args))

    #1
    # api = freeswitch.API()  ##freeswitch的API
    # regStatus = api.executeString("sofia status profile internal reg " + args)
    # freeswitch.consoleLog("ERR", "regStatus: %s \n" % regStatus)
    # beginIndex = regStatus.find("User:")  ##截取字符串
    # if beginIndex > -1:  ##假如不为None,就是已经注册在线
    #     ##获取注册
    #     beginIndex = regStatus.find(args + "@")
    #     endIndex = regStatus.find("Contact:")
    #     freeswitch.consoleLog("NOTICE", "endIndex: %s \n" % str(endIndex))
    #     regRealm = regStatus[beginIndex:endIndex]
    #     regRealm = regRealm.strip("\n")
    #     #1004@testfs.ihk.cn
    #     freeswitch.consoleLog("NOTICE", "reg user: " + args + ", realm : " + regRealm)
    # else:
    #     freeswitch.consoleLog("ERR", "user " + args + "尚未注册")
    #     session.hangup("USER_NOT_REGISTERED")
    try:

        session.setVariable("continue_on_fail", "false")
        session.setVariable("hangup_after_bridge", "true")
        session.setVariable("jitterbuffer_msec", "260:400:20")
        session.setVariable("rtp_jitter_buffer_during_bridge", "true")
        session.execute("export", "session_id=${uuid}")
        session.execute("export", "call_timeout=60")
        #TODO 返回180，200OK
        # session.execute("ring_ready", "")
        # TODO ????勾无效？
        session.setHangupHook("hangup_hook")

        # save record file
        today = time.strftime("%Y%m%d", time.localtime())
        record_path_index = random.choice([0, 1])
        if record_path_index is 0:
            session.setVariable("sip_h_X-record_file_path","https://testfs.ihk.cn:8889/fsm/freeswitchRecord/"+ today + "/" + uuid + ".wav")
        elif record_path_index is 1:
            session.setVariable("sip_h_X-record_file_path","https://testfs.ihk.cn:8889/fsm/freeswitchRecord51/"+ today + "/" + uuid + ".wav")
        #/cloudcall_file/rec_20051/freeswitchRecordFile/20200410/818dac4d-b5b8-4e7f-a7b6-af021d62165a.wav
        path = record_save_base_paths[record_path_index] + today + "/" + uuid + ".wav"
        session.execute("export", "nolocal:execute_on_answer=record_session " + path)
        freeswitch.console_log("info", "choice path: %s \n" % path)

        call_str = "user/%s" % args
        freeswitch.console_log("NOTICE", "bridge string is: %s \n" % call_str)
        # session.execute("bridge", "user/%s" % args)
        session.execute("bridge", call_str)
        session.hangup()
    except Exception as err:
        freeswitch.console_log("err", "call %s exception,msg: %s \n" % (uuid, str(err)))
        session.hangup("ORIGINATOR_CANCEL")


def hangup_hook(uuid):
    freeswitch.console_log("info", "myHangupHook, uuid: %s!!\n" % uuid)
    return "Result"
